package com.authority.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.authority.common.AdminConstants;
import com.authority.common.UserTypeEnum;
import com.authority.dao.AuthRoleDAO;
import com.authority.dao.AuthUserDAO;
import com.authority.dao.AuthUserDataDao;
import com.authority.entry.AuthSysDO;
import com.authority.entry.AuthUserDO;
import com.authority.result.BasicResult;
import com.authority.service.AuthSysService;
import com.authority.service.UserService;
import com.authority.utils.TokenUtils;
import com.authority.vo.AuthUserVO;
import com.google.common.base.Preconditions;
import com.google.gson.Gson;

public class BaseManager {
	@Resource
	HttpServletRequest request;

	@Resource
	HttpServletResponse response;

	@Resource
	HttpSession session;
	@Resource
	private UserService userService;
	@Resource
	private AuthUserDataDao authUserDataDao;
	@Resource
	private AuthRoleDAO authRoleDAO;
	@Resource
	private AuthSysService authSysService;
	@Resource
	private AuthUserDAO authUserDAO;
	
	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}
	
	public HttpServletRequest getRequest() {
		return request;
	}
	
	protected final static Logger logger = LoggerFactory.getLogger(BaseManager.class); 
	
	protected Long getUserId(){
		return TokenUtils.getUid(session.getAttribute("token").toString());
	}
	
	protected String getAccount(){
		return TokenUtils.getAccount(session.getAttribute("token").toString());
	}
	
	protected Integer getType(){
		return TokenUtils.getType(session.getAttribute("token").toString());
	}
	/**
	 * 获取用户名称
	 * @return
	 * 2016年4月29日 下午2:19:40
	 * houchu.zjj
	 */
	protected String getUsername(){
	    Object attribute = session.getAttribute("username");
	    if(attribute==null){
		return getAccount();
	    }else{
		return attribute.toString();
	    }
	}

	protected <T> BasicResult<T> success(T t) {
		BasicResult<T> res = new BasicResult<T>();
		res.setInfo(t);
		return res;
	}

	protected BasicResult<Void> success() {
		BasicResult<Void> res = new BasicResult<Void>();
		res.setInfo(null);
		return res;
	}

	protected <T> BasicResult<T> fail(Exception e, int code) {
		BasicResult<T> res = new BasicResult<T>();
		res.setCode(code);
		res.setMsg(e);
		return res;
	}

	protected <T> BasicResult<T> fail(Exception e) {
		//e.printStackTrace();
		BasicResult<T> res = new BasicResult<T>();
		res.setCode(AdminConstants.CODE_500);
		res.setMsg(e);
		return res;
	}
	
	protected <T> BasicResult<T> fail(String msg) {
		BasicResult<T> res = new BasicResult<T>();
		res.setCode(AdminConstants.CODE_500);
		res.setMsg(msg);
		return res;
	}
	
	/**
	 * 必要参数检查
	 * @param o
	 */
	public void checkParams(Object... params){
		for(Object o : params){
			Preconditions.checkNotNull(o,"必要参数不存在");
		}	
	}
	
	public <T> T checkParam(String param,Class<T> clazz) throws Exception {
		T t = null;
		if (param == null) {
			t = clazz.newInstance();
		}else {
			t = (T) new Gson().fromJson(param, clazz);
		}
		return t;
	}
	
	/**
	 * 必要参数检查
	 * @param o
	 */
	public boolean checkRight(){
		if(session==null || session.getAttribute("userPrivilegeUrls")==null || request==null || request.getRequestURI()==null)
			return false;
		String urls = String.valueOf(session.getAttribute("userPrivilegeUrls"));
		String uri = request.getRequestURI().trim();
		String ContextUrl = request.getContextPath();
		String [] authorityUrl = urls.split(",");
		for(String url:authorityUrl){
			url = new StringBuffer().append(ContextUrl).append(url.trim()).toString();
			if(uri.equals(url)){
				return true ;
			}
		}
		return false;
	}
	/**
	 * <p>Title: checkCount</p>
	 * <p> 功能描述:校验微运营过来的账户和密码 </p>
	 * @param name
	 * @param password
	 * @return
	 */
	public Integer checkCount(String account,String password) {
		return userService.checkByAppAccount(account, password);
	}
	
	public Long getSysId() {
		AuthSysDO sys = authSysService.queryAuthSysByCode(AdminConstants.SYSTEM_CODE);
		if(null!=sys){
			return sys.getId();
		}
		return null;
	}
	
	/**
	 * <p>Title: toRedirect</p>
	 * <p> 功能描述:重定向页面 </p>
	 * @param errorCode
	 */
	public void toRedirect(int errorCode) {
		try {
			if (!getResponse().isCommitted()) {
				getResponse().sendRedirect(getRequest().getContextPath()+"/errorpage/"+errorCode+".html");
			}
		} catch (IOException e) {
			logger("redirectException:"+e.getMessage(),e);
		}
	}

/*	protected void createResponse(String callback, Object object, Context context) {
		String jsonString = JSON.toJSONStringWithDateFormat(object, "yyyy-MM-dd HH:mm:ss");
		if(StringUtils.isNotEmpty(callback)) {
			context.put("json", "\n " + SecurityUtil.richtext(callback) + "(" + jsonString + ")");
		} else {
			context.put("json", "\n " + jsonString);
		}
	}*/
	
	/**
	 * 获取设备类型
	 */
	public String getDeviceTypename(int deviceType){
	    if(1==deviceType)
	    	return "手表";
	    else if(2==deviceType)
	    	return "智能学生证";
	    else if(3==deviceType)
	    	return "考勤卡";
	    else
	    	return "";
	    
	}
	/**
	 * 获取缴费状态
	 */
	public String getPayStatusName(int payStatus){
	    if(1==payStatus)
	    	return "未激活";
	    else if(2==payStatus)
	    	return "已激活";
	    else if(3==payStatus)
	    	return "已缴费";
	    else
	    	return "已过期";
	    
	}
	/**
	 * <p>Title: logger</p>
	 * <p> 功能描述:记录日志 </p>
	 * @param message
	 */
	public void logger(String message,Exception e) {
		if (logger.isDebugEnabled()) {
			logger.debug(message,e);
		}
		if (logger.isErrorEnabled()) {
			logger.error(message,e);
		}
	}
	
	/**
	 * 生成excel对象,40000条数据内
	 * 
	 * @return
	 */
	public HSSFWorkbook exportDeviceList(String title,ArrayList<String> listParm,List<List<String>> listValue) throws Exception{
		// 创建新的Excel 工作簿
		HSSFWorkbook workbook = new HSSFWorkbook();
		if (listParm == null || listValue==null)
			return workbook ;
			// 在Excel工作簿中建一工作表，其名为缺省值
			HSSFSheet sheet = workbook.createSheet();
			// 在工作薄中建立工作表
			workbook.setSheetName(0, title);// 设置表格标题及编码格式
			// 在索引0的位置创建行（最顶端的行）
			HSSFCell cell = null;
			HSSFRow row = sheet.createRow((short) 0);
			//设置字体颜色为红色
			HSSFCellStyle style = workbook.createCellStyle(); 
			HSSFFont font = workbook.createFont(); 
			font.setFontHeightInPoints((short) 12);//字号       
			style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//左右居中  
			String[] arrys1 = new String[listParm.size()];// 表格题头
			listParm.toArray(arrys1);
			for (int i = 0; i < listParm.size(); i++) {
				if("学校列表".contains(title)){
					sheet.setColumnWidth(i, 11000);
				}else{
					sheet.setColumnWidth(i, 4500);
				}
				cell = row.createCell(Short.parseShort((i) + ""));
				cell.setCellValue(arrys1[i]);
				style.setFont(font);
				cell.setCellStyle(style);  
			}
			for (int i = 0; i < listValue.size(); i++) {
				row = sheet.createRow(i + 1);
				List<String> map = listValue.get(i);
				for (int j = 0; j < map.size(); j++) {
					if("学校列表".contains(title)){
						sheet.setColumnWidth(i, 11000);
					}else{
						sheet.setColumnWidth(i, 4500);
					}
					cell = row.createCell(Short.parseShort(j + ""));
					cell.setCellValue(map.get(j));
					font.setFontHeightInPoints((short) 11);//字号       
					style.setFont(font);
					cell.setCellStyle(style);  
				}
			}
		return workbook;
	}
	/**
	 * 生成excel对象,带示例（用于导出excel模板）
	 * 
	 * @return
	 */
	public HSSFWorkbook exportDeviceList(String title,ArrayList<String> listParm,ArrayList<String> listExample,List<List<String>> listValue) throws Exception{
		
		// 创建新的Excel 工作簿
				HSSFWorkbook workbook = new HSSFWorkbook();
				if (listParm == null || listValue==null)
					return workbook ;
					// 在Excel工作簿中建一工作表，其名为缺省值
					HSSFSheet sheet = workbook.createSheet();
					// 在工作薄中建立工作表
					workbook.setSheetName(0, title);// 设置表格标题及编码格式
					// 在索引0的位置创建行（最顶端的行）
					HSSFCell cell = null;
					HSSFRow row1 = sheet.createRow((short) 0);
					
					String[] arrys1 = new String[listParm.size()];// 表格题头
					listParm.toArray(arrys1);
					for (int i = 0; i < listParm.size(); i++) {
						sheet.setColumnWidth(i, 5500);
						cell = row1.createCell(Short.parseShort((i) + ""));
						cell.setCellValue(arrys1[i]);
						//设置字体颜色为红色
						HSSFCellStyle style = workbook.createCellStyle(); 
						HSSFFont font = workbook.createFont(); 
						font.setColor(HSSFColor.RED.index);
						font.setFontHeightInPoints((short) 12);//字号       
						font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);//加粗       
						style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//左右居中  
						style.setFont(font);
						cell.setCellStyle(style);  
					}
					

					HSSFRow row2 = sheet.createRow((short) 1);
					String[] arrys2 = new String[listExample.size()];// 表格示例
					listExample.toArray(arrys2);
					for (int i = 0; i < listExample.size(); i++) {
						sheet.setColumnWidth(i, 5500);
						cell = row2.createCell(Short.parseShort((i) + ""));
						cell.setCellValue(arrys2[i]);
						//设置字体颜色为红色
						HSSFCellStyle style = workbook.createCellStyle(); 
						HSSFFont font = workbook.createFont(); 
						style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//左右居中  
						style.setFont(font);
						cell.setCellStyle(style);  
					}
					
					for (int i = 0; i < listValue.size(); i++) {
						row1 = sheet.createRow(i + 1);
						row2 = sheet.createRow(i + 1);
						List<String> map = listValue.get(i);
						for (int j = 0; j < map.size(); j++) {
							sheet.setColumnWidth(i, 5500);
							cell = row1.createCell(Short.parseShort(j + ""));
							cell = row2.createCell(Short.parseShort(j + ""));
							cell.setCellValue(map.get(j));
							//设置字体颜色为红色
							HSSFCellStyle style = workbook.createCellStyle(); 
							HSSFFont font = workbook.createFont(); 
							font.setFontHeightInPoints((short) 11);//字号       
							style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//左右居中  
							style.setFont(font);
							cell.setCellStyle(style);  
						}
					}
					
				return workbook;
	}
	
	
	public boolean isAdmin() {
		logger.info("用户的id为："+getUserId());
		AuthUserVO user = userService.queryUserById(getUserId(),false);
		if (user != null && user.getType() == UserTypeEnum.ADMIN.getType()) {
			return true;
		}else {
			return false;
		}
	}
	
	public boolean chechAuthority(Long userId) {
		Integer count = authUserDataDao.countByUserId(userId);
		if (count == null || count == 0) {
			return false;
		}else {
			return true;
		}
	}
	
	public int getUserType(Long userId) {
		AuthUserDO userDo = authUserDAO.queryUserById(userId);
		if (userDo != null) {
			return userDo.getType();
		}
		return 0;
	}
	
}
